﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml;
using System.Xml.Serialization;
using Anthony.Library.Entensions;

namespace Anthony.Library
{
    /// <summary>
    /// 
    /// </summary>
    public class XmlSerializing
    {


        /// <summary>
        /// Converts a custom Object to XML string.
        /// </summary>
        /// <param name="o">Object to serialize to XML.</param>
        /// <param name="type">Type to serialize to.</param>
        /// <returns></returns>
        public static string ToXml(object o, Type type)
        {
            MemoryStream stream = new MemoryStream();
            XmlSerializer serializer = new XmlSerializer(type);
            XmlTextWriter writer = new XmlTextWriter(stream, Encoding.UTF8);

            // serialize to xml
            serializer.Serialize(writer, o);

            // get stream
            stream = (MemoryStream)writer.BaseStream;

            // convert to string and return
            string xml = stream.ToArray().UTF8ByteArrayToString();

            // TODO: there was some strange character at position 0 which gets coded into a '?' on save to the db.
            // this is a hack to get rid of it.
            int start = xml.IndexOf('<');

            return xml.Substring(start != -1 ? start : 0, xml.Length - 1);
        }


        /// <summary>
        /// Deserializes XML string.
        /// </summary>
        /// <param name="xml">Xml to deserialize.</param>
        /// <param name="type">Type to deserialize to.</param>
        /// <returns></returns>
        public static object FromXml(string xml, Type type)
        {
            XmlSerializer serializer = new XmlSerializer(type);
            MemoryStream stream = new MemoryStream(xml.ToUTF8ByteArray());
            XmlTextWriter xmlTextWriter = new XmlTextWriter(stream, Encoding.UTF8);

            return serializer.Deserialize(stream);
        }

    }
}
